﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web;
using System.IO;
using System.Xml;
using Microsoft.SharePoint.Utilities;

namespace UserControlFormSolution
{

    public class UserControlForm : UserControl
    {
        /// <summary>
        /// This property will hold the name of the List to store the data in. 
        /// </summary>
        public string ListName { get; set; }

        /// <summary>
        /// This property will hold the full Url of the SubWeb in which the List resides.
        /// </summary>
        public string WebUrl { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        /// <summary>
        /// This method will be called upon clicking on the front-end-button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Save_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && !string.IsNullOrEmpty(ListName) && !string.IsNullOrEmpty(WebUrl))
            {
                IFormProcessor processor = new WebServiceListStoreProcessor();
                processor.Prepare(WebUrl, ListName,UserName,Password);

                foreach (Control entrycontrol in Controls)
                {
                    string value = HttpContext.Current.Request.Form[entrycontrol.UniqueID];
                    
                    if (entrycontrol is System.Web.UI.WebControls.FileUpload)
                    {
                        System.Web.UI.WebControls.FileUpload fucontrol = (System.Web.UI.WebControls.FileUpload)entrycontrol;
                        if (fucontrol.PostedFile != null && fucontrol.PostedFile.ContentLength > 0)
                        {
                            byte[] fudata = new byte[fucontrol.PostedFile.InputStream.Length];
                            fucontrol.PostedFile.InputStream.Read(fudata, 0, fudata.Length);
                            processor.AddAttachment(System.IO.Path.GetFileName(fucontrol.PostedFile.FileName), fudata);
                        }
                    }
                    else
                    {
                        // Check if this Control has an ID which is required to identify a destination field
                        if (!string.IsNullOrEmpty(entrycontrol.ID))
                        {
                            processor.AddField(entrycontrol.ID, value);
                        }
                    }
                }
                processor.Finish();
            }
        }
    }
}
